<template>
  <div class="canton-fair-exhibitors-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader />
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu />
      
      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('canton.exhibitor.search.title') }}</div>
          
          <!-- 搜索输入区 -->
          <div class="search-box-container">
            <el-input
              v-model="searchKeyword"
              :placeholder="t('canton.exhibitor.search.placeholder')"
              clearable
              class="search-input"
              @clear="resetSearch"
              @keyup.enter="handleSearch"
              prefix-icon="el-icon-search"
            >
            </el-input>

            <el-input
              v-model="searchProduct"
              :placeholder="t('canton.exhibitor.search.product')"
              clearable
              class="search-input"
              @clear="resetSearch"
              @keyup.enter="handleSearch"
              prefix-icon="el-icon-search"
            >
            </el-input>
<!--            <el-input-->
<!--              v-model="searchProduct"-->
<!--              :placeholder="t('canton.exhibitor.search.product')"-->
<!--              clearable-->
<!--              class="search-input"-->
<!--              @clear="resetSearch"-->
<!--              @keyup.enter="handleSearch"-->
<!--              prefix-icon="el-icon-search"-->
<!--            >-->
<!--            </el-input>-->
          </div>
        </div>
        
        <!-- 主内容区域 - 左侧筛选器 + 右侧卡片列表 -->
        <div class="exhibitors-main">
          <!-- 左侧筛选器，添加固定效果 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters" class="reset-filter-btn">
                  {{ t('canton.exhibitor.reset.filters') }}
                </el-button>
              </div>
              
              <!-- 广交会届数筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.sessionInfo }">
                <div class="filter-header" @click="toggleFilter('sessionInfo')">
                  <span>{{ t('canton.exhibitor.session') }}</span>
                  <i :class="['el-icon', expanded.sessionInfo ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.sessionInfo" class="filter-content">
                  <el-radio-group v-model="selectedSession" @change="handleSessionChange">
                    <el-radio label="">{{ t('canton.exhibitor.all.sessions') }}</el-radio>
                    <el-radio label="125">{{ t('canton.exhibitor.session.number', {number: '125'}) }}</el-radio>
                    <el-radio label="126">{{ t('canton.exhibitor.session.number', {number: '126'}) }}</el-radio>
                    <el-radio label="127">{{ t('canton.exhibitor.session.number', {number: '127'}) }}</el-radio>
                    <el-radio label="128">{{ t('canton.exhibitor.session.number', {number: '128'}) }}</el-radio>
                    <el-radio label="129">{{ t('canton.exhibitor.session.number', {number: '129'}) }}</el-radio>
                    <el-radio label="130">{{ t('canton.exhibitor.session.number', {number: '130'}) }}</el-radio>
                    <el-radio label="134">{{ t('canton.exhibitor.session.number', {number: '134'}) }}</el-radio>
                    <el-radio label="135">{{ t('canton.exhibitor.session.number', {number: '135'}) }}</el-radio>
                    <el-radio label="136">{{ t('canton.exhibitor.session.number', {number: '136'}) }}</el-radio>
                    <el-radio label="137">{{ t('canton.exhibitor.session.number', {number: '137'}) }}</el-radio>
                    <el-radio label="138">{{ t('canton.exhibitor.session.number', {number: '138'}) }}</el-radio>
                  </el-radio-group>
                </div>
              </div>
              
              <!-- 企业类型筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.companyType }">
                <div class="filter-header" @click="toggleFilter('companyType')">
                  <span>{{ t('canton.exhibitor.company.type') }}</span>
                  <i :class="['el-icon', expanded.companyType ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.companyType" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search">
                    <el-input 
                      v-model="companyTypeSearch" 
                      :placeholder="t('canton.exhibitor.company.type.placeholder')" 
                      size="small" 
                      clearable
                      prefix-icon="el-icon-search"
                    ></el-input>
                  </div>
                  
                  <el-checkbox :indeterminate="isIndeterminate.companyType" v-model="checkAll.companyType" @change="handleCheckAllChange('companyType')">{{ t('canton.exhibitor.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.companyType" @change="handleFilterChange('companyType')">
                    <el-checkbox v-for="item in filteredCompanyTypes" 
                      :key="item" 
                      :value="item">
                      {{ getLocalizedCompanyType(item) }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              
              <!-- 企业规模筛选 -->
              <div class="filter-group" :class="{ expanded: expanded.companyScale }">
                <div class="filter-header" @click="toggleFilter('companyScale')">
                  <span>{{ t('canton.exhibitor.company.scale') }}</span>
                  <i :class="['el-icon', expanded.companyScale ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.companyScale" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search">
                    <el-input 
                      v-model="companyScaleSearch" 
                      :placeholder="t('canton.exhibitor.company.scale.placeholder')" 
                      size="small" 
                      clearable
                      prefix-icon="el-icon-search"
                    ></el-input>
                  </div>
                  
                  <el-checkbox :indeterminate="isIndeterminate.companyScale" v-model="checkAll.companyScale" @change="handleCheckAllChange('companyScale')">{{ t('canton.exhibitor.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.companyScale" @change="handleFilterChange('companyScale')">
                    <el-checkbox v-for="item in filteredCompanyScales" 
                      :key="item" 
                      :value="item">
                      {{ getLocalizedCompanyScale(item) }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group" :class="{ expanded: expanded.contact }">
                <div class="filter-header" @click="toggleFilter('contact')">
                  <span>{{ t('canton.exhibitor.filter.contact') }}</span>
                  <i :class="['el-icon', expanded.contact ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.contact" class="filter-content">
                  <el-checkbox-group v-model="filters.contact" @change="handleContactChange">
                    <el-checkbox value="phone">{{ t('canton.exhibitor.filter.contact.phone') }}</el-checkbox>
                    <el-checkbox value="mobile">{{ t('canton.exhibitor.filter.contact.mobile') }}</el-checkbox>
                    <el-checkbox value="fax">{{ t('canton.exhibitor.filter.contact.fax') }}</el-checkbox>
                    <el-checkbox value="email">{{ t('canton.exhibitor.filter.contact.email') }}</el-checkbox>
                    <el-checkbox value="website">{{ t('canton.exhibitor.filter.contact.website') }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 导出数据模块 -->
            <div class="export-module">
              <div class="export-info">
                <span>{{ t('canton.exhibitor.matching.records') }}: </span>
                <span class="export-count">{{ totalExhibitors >= 10000 ? '10,000+' : totalExhibitors }}</span>
              </div>
              <el-button @click="exportData" class="export-module-btn" type="primary" :loading="exportLoading">
                  <el-icon><Download /></el-icon>
                  {{ t('canton.exhibitor.export.data') }}
                </el-button>
            </div>
            
            <!-- 参展商列表 -->
            <div v-loading="loading" class="exhibitor-card-list">
              <!-- 无数据提示 -->
              <div v-if="!loading && filteredExhibitors.length === 0" class="no-data">
                <i class="el-icon-warning-outline"></i>
                <p>{{ errorMsg || t('canton.exhibitor.no.data') }}</p>
                <div>
                  <el-button @click="resetAllFilters" type="primary" size="small" class="mt-3 mr-2">
                    {{ t('canton.exhibitor.reset.filters') }}
                  </el-button>
                  <el-button @click="fetchExhibitors" type="info" size="small" class="mt-3">
                    {{ t('canton.exhibitor.reload') }}
                  </el-button>
                </div>
              </div>
              
              <!-- 骨架屏 -->
              <div v-if="loading && filteredExhibitors.length === 0" class="skeleton-loading">
                <div v-for="i in 6" :key="i" class="skeleton-card">
                  <div class="skeleton-header">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-title"></div>
                  </div>
                  <div class="skeleton-content">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                  </div>
                </div>
              </div>
              
              <!-- 采购商卡片 -->
              <div 
                v-for="(exhibitor, index) in paginatedExhibitors" 
                :key="index" 
                class="exhibitor-card"
              >
                <!-- 卡片头部 - 显示公司名称 -->
                <div class="card-header">
                  <div class="company-info">
                    <div class="company-avatar">
                      <img 
                        :src="getAvatarUrl(exhibitor.companyName)" 
                        class="cartoon-avatar" 
                        :alt="exhibitor.companyName"
                        @error="handleAvatarError"
                      />
                    </div>
                    <div class="company-name">{{ exhibitor.companyName || t('canton.exhibitor.unknown') }}</div>
                  </div>
                </div>
                
                <!-- 分隔线 -->
                <div class="card-divider"></div>
                
                <!-- 基本信息和详情按钮并排显示 -->
                <div class="info-button-container">
                  <!-- 基本信息区域 -->
                  <div class="card-basic-info">
                    <div class="basic-info-grid">
                      <div class="info-row">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.exhibitor.session.info') }}</span>
                          <span class="info-value" v-if="exhibitor.sessionInfo">{{ exhibitor.sessionInfo || t('canton.exhibitor.unknown.value') }}</span>
<!--                          <span class="info-value" v-else>{{ exhibitor.session || t('canton.exhibitor.unknown.value') }}</span>-->
                        </div>
                      </div>
                      <div class="info-row" v-if="exhibitor.companyScale">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.exhibitor.company.scale.info') }}</span>
                          <span class="info-value">{{ getLocalizedCompanyScale(exhibitor.companyScale) }}</span>
                        </div>
                      </div>
                      <div class="info-row" v-if="exhibitor.enterpriseType || exhibitor.companyType">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.exhibitor.company.type.info') }}</span>
                          <span class="info-value">{{ getLocalizedCompanyType(exhibitor.enterpriseType || exhibitor.companyType) }}</span>
                        </div>
                      </div>
                      <div class="info-row" v-if="exhibitor.category">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.exhibitor.category') }}:</span>
                          <span class="info-value">{{ exhibitor.category }}</span>
                        </div>
                      </div>
                      <div class="info-row" v-if="exhibitor.mainProducts ">
                        <div class="info-item full-width">
                          <span class="info-label">{{ t('canton.exhibitor.main.products') }}</span>
                          <span class="info-value">{{ exhibitor.mainProducts }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 详情按钮 -->
                  <div class="detail-button-container">
                    <el-button @click="toggleExhibitorDetails(exhibitor)" class="detail-btn" type="primary" plain>
                      {{ exhibitor.expanded ? t('canton.exhibitor.collapse') : t('canton.exhibitor.details') }}
                    </el-button>
                  </div>
                </div>
                
                <!-- 详细内容 - 点击详情后显示 -->
                <div class="card-content" v-show="exhibitor.expanded">
                  <div class="detail-title">{{ t('canton.exhibitor.detail.title') }}</div>
                  <!-- 参展商详细信息 -->
                  <div class="info-table-wrapper">
                    <table class="info-table">
                      <tbody>
                        <tr v-if="exhibitor.period">
                          <td class="label-cell">{{ t('canton.exhibitor.booth.period') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.period }}</td>
                        </tr>
                        <tr v-if="exhibitor.boothNumber || exhibitor.boothNo">
                          <td class="label-cell">{{ t('canton.exhibitor.booth.number') }}</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.boothNumber || exhibitor.boothNo }}</td>
                        </tr>
                        <tr v-if="exhibitor.contactPerson">
                          <td class="label-cell">{{ t('canton.exhibitor.contact.person') }}</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.contactPerson }}</td>
                        </tr>
                        <tr v-if="exhibitor.principalName">
                          <td class="label-cell">{{ t('canton.exhibitor.contact.principalName') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.principalName }}</td>
                        </tr>
                        <tr v-if="exhibitor.principalPosition">
                          <td class="label-cell">{{ t('canton.exhibitor.contact.principalPosition') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.principalPosition }}</td>
                        </tr>

                        <tr v-if="exhibitor.mobilePhone">
                          <td class="label-cell">{{ t('canton.exhibitor.mobile') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.mobilePhone && exhibitor.mobilePhone.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'mobilePhone')">
                                {{ exhibitor.mobilePhone }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.mobilePhone }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.phone">
                          <td class="label-cell">{{ t('canton.exhibitor.phone') }}</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.phone && exhibitor.phone.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'phone')">
                                {{ exhibitor.phone }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.phone }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.principalPhone">
                          <td class="label-cell">{{ t('canton.exhibitor.principalPhone') }}:</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.principalPhone && exhibitor.principalPhone.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'principalPhone')">
                                {{ exhibitor.principalPhone }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.principalPhone }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.principalMobile">
                          <td class="label-cell">{{ t('canton.exhibitor.principalMobile') }}:</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.principalMobile && exhibitor.principalMobile.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'principalMobile')">
                                {{ exhibitor.principalMobile }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.principalMobile }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.fax">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.fax') }}:</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.fax && exhibitor.fax.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'fax')">
                                {{ exhibitor.fax }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.fax }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.email">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.email') }}:</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.email && exhibitor.email.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'email')">
                                {{ exhibitor.email }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <span v-else>{{ exhibitor.email }}</span>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.website">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.website') }}:</td>
                          <td class="value-cell" colspan="3">
                            <el-tooltip
                              v-if="exhibitor.website && exhibitor.website.includes('*')"
                              :content="t('canton.exhibitor.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                            >
                              <span 
                                class="masked-info"
                                @click="showFullContactInfo(exhibitor, 'website')">
                                {{ exhibitor.website }}
                                <el-icon class="info-lock-icon"><Lock /></el-icon>
                              </span>
                            </el-tooltip>
                            <a v-else :href="addHttpPrefix(exhibitor.website)" target="_blank">{{ exhibitor.website }}</a>
                          </td>
                        </tr>
                        <tr v-if="exhibitor.address">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.address') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.address }}</td>
                        </tr>
                        <tr v-if="exhibitor.postalCode">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.postalCode') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.postalCode }}</td>
                        </tr>
                        <tr v-if="exhibitor.province">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.province') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.province || '' }}</td>
                        </tr>
                        <tr v-if="exhibitor.city">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.city') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.city || '' }}</td>
                        </tr>
                        <tr v-if="exhibitor.registeredCapital">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.registeredCapital') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.registeredCapital }}</td>
                        </tr>
                        <tr v-if="exhibitor.establishYear">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.year') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.establishYear }}</td>
                        </tr>
                        <tr v-if="exhibitor.recentExhibitionHistory">
                          <td class="label-cell">{{ t('canton.exhibitor.establish.recentExhibitionHistory') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.recentExhibitionHistory }}</td>
                        </tr>
                        <tr v-if="exhibitor.establishmentYear">
                          <td class="label-cell">{{ t('canton.exhibitor.establishmentYear') }}:</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.establishmentYear }}</td>
                        </tr>
                        <tr v-if="exhibitor.companyProfile">
                          <td class="label-cell">{{ t('canton.exhibitor.companyProfile') }}</td>
                          <td class="value-cell" colspan="3">{{ exhibitor.companyProfile }}</td>
                        </tr>
                        <tr v-if="exhibitor.companyScale || exhibitor.enterpriseScale">
                          <td class="label-cell">{{ t('canton.exhibitor.company.scale.info') }}</td>
                          <td class="value-cell" colspan="3">{{ getLocalizedCompanyScale(exhibitor.companyScale || exhibitor.enterpriseScale) }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="sizes, prev, pager, next, jumper"
                :total="Math.min(Math.max(totalExhibitors, 1), 10000)"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
                background
                :pager-count="7"
                :disabled="loading"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 导出对话框 -->
  <el-dialog
    v-model="exportDialogVisible"
    :title="t('export.dialog.title')"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('export.matching.records') }}: <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>{{ t('export.current.balance') }}: <span class="export-highlight">{{ userBalance.exportQuotaRemaining || 0 }}</span></p>
        <p class="export-note">{{ t('export.note') }}</p>
        <p class="export-limit-notice">{{ t('export.max.limit.notice') }}</p>
      </div>

      <!-- 字段选择区域 -->
      <div class="field-selection">
        <div class="field-selection-header">
          <h4>{{ t('export.selectFields') }}</h4>
          <div class="field-selection-actions">
            <el-button
              size="small"
              @click="selectAllFields"
              :disabled="isAllFieldsSelected"
            >
              {{ t('export.selectAll') }}
            </el-button>
            <el-button
              size="small"
              @click="selectNoFields"
              :disabled="isNoFieldsSelected"
            >
              {{ t('export.selectNone') }}
            </el-button>
          </div>
        </div>

        <div class="field-selection-content">
          <div class="field-grid">
            <div
              v-for="field in allFields"
              :key="field.key"
              class="field-item"
            >
              <el-checkbox
                v-model="field.selected"
                @change="updateSelectedFields"
              >
                <span :class="{ 'field-unselected': !field.selected }">
                  {{ t(field.labelKey) }}
                </span>
              </el-checkbox>
            </div>
          </div>

          <div v-if="isNoFieldsSelected" class="field-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.noFieldsSelected') }}
          </div>
        </div>
      </div>

      <div class="export-input">
        <p>{{ t('export.enter.count') }}</p>
        <el-input-number
          v-model="exportCount"
          :min="1"
          :max="Math.max(1, Math.min(totalMatchCount, 1000000))"
          :step="100"
          size="large"
          controls-position="right"
          @change="validateExportCount"
        />
        
        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.exceed') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.balance') }}
          </p>
          <p v-if="isExportLimitExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.limit') }}
          </p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('export.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="doExport"
          :loading="exportLoading"
          :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount || isNoFieldsSelected"
        >
          {{ t('export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Check, WarningFilled, Refresh, Lock } from '@element-plus/icons-vue'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { getCantonFairExhibitors, exportCantonFairExhibitors, getCantonFairExhibitorsCount, getUserBalanceInfo, getExhibitorFullContactInfo } from '@/api/exhibitors'
import { t, getCurrentLanguage, addTranslation, currentLanguage as globalCurrentLanguage } from '@/utils/i18n'  // 导入t函数、getCurrentLanguage函数和addTranslation函数

export default {
  name: 'CantonFairExhibitors',
  components: {
    MainHeader,
    SideMenu,
    Download,
    Check,
    WarningFilled,
    Refresh,
    Lock
  },
  setup() {
    const loading = ref(false)
    const exportLoading = ref(false)
    const exhibitors = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalExhibitors = ref(0)
    const errorMsg = ref('')
    const searchKeyword = ref('')
    const searchProduct = ref('')
    const selectedSession = ref('') // 选中的广交会届数

    // 企业类型中英文映射 - 完整的企业类型翻译
    const COMPANY_TYPE_TRANSLATIONS = {
      // 基础选项
      '未知': 'Unknown',
      '--': '--',
      '-': '-',
      '': 'Unknown',
      'null': 'Unknown',

      // 国有和集体企业
      '国有企业': 'State-owned Enterprise',
      '集体企业': 'Collective Enterprise',

      // 私营和股份制企业
      '私营企业': 'Private Enterprise',
      '有限责任公司': 'Limited Liability Company',
      '股份有限公司': 'Joint Stock Company',
      '股份合作企业': 'Cooperative Share Enterprise',
      '联营企业': 'Joint Venture',

      // 外资企业
      '中外合资企业': 'Sino-foreign Joint Venture',
      '中外合作企业': 'Sino-foreign Cooperative Enterprise',
      '外商独资企业': 'Foreign-owned Enterprise',
      '港澳台投资企业': 'Hong Kong, Macao and Taiwan Investment Enterprise',

      // 专业类型企业
      '生产企业': 'Manufacturing Enterprise',
      '外贸企业': 'Foreign Trade Enterprise',
      '工贸企业': 'Industry and Trade Enterprise',
      '科研院所': 'Research Institute',

      // 其他
      '其他企业': 'Other Enterprise'
    };
    
    // 企业规模中英文映射 - 根据新的企业规模选项更新
    const COMPANY_SCALE_TRANSLATIONS = {
      // 新的企业规模选项映射
      '未知': 'Unknown',
      '少于50人': 'Less than 50 Employees',
      '1-50人': '1-50 Employees',
      '51-100人': '51-100 Employees',
      '50~150': '50-150 Employees',
      '101-500人': '101-500 Employees',
      '150~500': '150-500 Employees',
      '500人以上': '500+ Employees',
      '500~1000': '500-1000 Employees',
      '1000~5000': '1000-5000 Employees',
      '5000~10000': '5000-10000 Employees',
      '10000人以上': '10000+ Employees',

      // 保留一些常见的兼容格式
      '--': '--',
      '': 'Unknown',
      'null': 'Unknown',
      '大型企业': 'Large Enterprise',
      '中型企业': 'Medium Enterprise',
      '小型企业': 'Small Enterprise',
      '微型企业': 'Micro Enterprise',
      '0-50人': '0-50 Employees',
      '1－50人': '1-50 Employees',
      '101－500人': '101-500 Employees',
      '501-999人': '501-999 Employees',
      '1000-4999人': '1000-4999 Employees',
      '5000人以上': '5000+ Employees',
      '＜50': '<50 Employees',
      '<50': '<50 Employees',
      '50-100': '50-100 Employees',
      '100-500': '100-500 Employees',
      '500+': '500+ Employees',
      '1000+': '1000+ Employees',
      '50-100人': '50-100 Employees',
      '100-200人': '100-200 Employees',
      '200-500人': '200-500 Employees',
      '500-1000人': '500-1000 Employees',
      '1000人以上': '1000+ Employees'
    };
    
    // 英文到中文的反向映射
    const REVERSE_COMPANY_TYPE_TRANSLATIONS = {};
    for (const [zhName, enName] of Object.entries(COMPANY_TYPE_TRANSLATIONS)) {
      REVERSE_COMPANY_TYPE_TRANSLATIONS[enName] = zhName;
    }

    const REVERSE_COMPANY_SCALE_TRANSLATIONS = {};
    for (const [zhName, enName] of Object.entries(COMPANY_SCALE_TRANSLATIONS)) {
      REVERSE_COMPANY_SCALE_TRANSLATIONS[enName] = zhName;
    }

    // 企业规模本地化显示函数
    const getLocalizedCompanyScale = (scale) => {
      if (!scale || scale === 'null' || scale === 'undefined') {
        return getCurrentLanguage() === 'en' ? 'Unknown' : '未知';
      }

      // 处理空字符串或仅包含空格的情况
      const trimmedScale = String(scale).trim();
      if (!trimmedScale || trimmedScale === '--') {
        return getCurrentLanguage() === 'en' ? 'Unknown' : '未知';
      }

      const currentLang = getCurrentLanguage();
      if (currentLang === 'en') {
        return COMPANY_SCALE_TRANSLATIONS[trimmedScale] || trimmedScale;
      } else {
        // 中文环境下，如果是英文值，尝试反向翻译
        return REVERSE_COMPANY_SCALE_TRANSLATIONS[trimmedScale] || trimmedScale;
      }
    }

    // 企业类型本地化显示函数
    const getLocalizedCompanyType = (type) => {
      if (!type || type === 'null' || type === 'undefined') {
        return getCurrentLanguage() === 'en' ? 'Unknown' : '未知';
      }

      const trimmedType = String(type).trim();
      if (!trimmedType || trimmedType === '--') {
        return getCurrentLanguage() === 'en' ? 'Unknown' : '未知';
      }

      const currentLang = getCurrentLanguage();
      if (currentLang === 'en') {
        return COMPANY_TYPE_TRANSLATIONS[trimmedType] || trimmedType;
      } else {
        return REVERSE_COMPANY_TYPE_TRANSLATIONS[trimmedType] || trimmedType;
      }
    }

    // 查询参数
    const queryParams = reactive({
      exhibitorName: '',
      sessionInfo: '',
      mainProducts: ''
    })
    
    // 筛选器展开状态
    const expanded = reactive({
      sessionInfo: true,
      companyType: true,
      companyScale: true,
      contact: true
    })
    
    // 筛选器选中状态
    const filters = reactive({
      companyType: [],
      companyScale: [],
      contact: []
    })
    
    // 全选状态
    const checkAll = reactive({
      companyType: false,
      companyScale: false
    })
    
    // 不确定状态（部分选中）
    const isIndeterminate = reactive({
      companyType: false,
      companyScale: false
    })
    
    // 筛选器搜索
    const companyTypeSearch = ref('')
    const companyScaleSearch = ref('')
    
    // 获取所有可选的筛选器选项
    const allFilterOptions = reactive({
      companyType: [],
      companyScale: []
    })
    
    // 根据搜索过滤筛选器选项
    const filteredCompanyTypes = computed(() => {
      // 获取当前语言
      const currentLang = getCurrentLanguage();
      
      // 筛选和本地化处理
      let filteredTypes = allFilterOptions.companyType;
      
      // 如果有搜索关键词，根据关键词筛选
      if (companyTypeSearch.value) {
        filteredTypes = filteredTypes.filter(item => {
          if (!item) return false;
          // 获取当前项的本地化文本
          const localizedItem = currentLang === 'en' ? 
            (COMPANY_TYPE_TRANSLATIONS[item] || item) : 
            (currentLang === 'zh' ? (REVERSE_COMPANY_TYPE_TRANSLATIONS[item] || item) : item);
          
          // 同时匹配原始文本和本地化文本
          return item.toLowerCase().includes(companyTypeSearch.value.toLowerCase()) || 
                 localizedItem.toLowerCase().includes(companyTypeSearch.value.toLowerCase());
        });
      }
      
      return filteredTypes;
    })
    
    const filteredCompanyScales = computed(() => {
      // 获取当前语言
      const currentLang = getCurrentLanguage();
      
      // 筛选和本地化处理
      let filteredScales = allFilterOptions.companyScale;
      
      // 如果有搜索关键词，根据关键词筛选
      if (companyScaleSearch.value) {
        filteredScales = filteredScales.filter(item => {
          if (!item) return false;
          // 获取当前项的本地化文本
          const localizedItem = currentLang === 'en' ? 
            (COMPANY_SCALE_TRANSLATIONS[item] || item) : 
            (currentLang === 'zh' ? (REVERSE_COMPANY_SCALE_TRANSLATIONS[item] || item) : item);
          
          // 同时匹配原始文本和本地化文本
          return item.toLowerCase().includes(companyScaleSearch.value.toLowerCase()) || 
                 localizedItem.toLowerCase().includes(companyScaleSearch.value.toLowerCase());
        });
      }
      
      return filteredScales;
    })
    
    // 根据筛选条件过滤参展商数据
    const filteredExhibitors = computed(() => {
      // 如果没有数据，直接返回空数组
      if (exhibitors.value.length === 0) {
        return [];
      }
      
      // 因为筛选条件已经传递给后端，前端只处理本地关键词搜索（如果有需要）
      let result = exhibitors.value;
      
      return result;
    })
    
    // 分页后的参展商数据
    const paginatedExhibitors = computed(() => {
      if (errorMsg.value) {
        return [];
      }
      
      if (filteredExhibitors.value.length === 0) {
        return [];
      }
      
      // 如果totalExhibitors大于filteredExhibitors的长度，说明是使用后端分页，直接返回
      if (totalExhibitors.value > filteredExhibitors.value.length && filteredExhibitors.value.length <= pageSize.value) {
        return filteredExhibitors.value;
      }
      
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredExhibitors.value.slice(start, end)
    })
    
    // 处理届数选择变化
    const handleSessionChange = (value) => {
      // 修改选中值并立即触发请求
      selectedSession.value = value;
      currentPage.value = 1; // 重置到第一页
      fetchExhibitors();
    }
    
    // 重置所有筛选条件
    const resetAllFilters = () => {
      // 重置搜索框
      searchKeyword.value = '';
      searchProduct.value = '';
      queryParams.exhibitorName = '';
      queryParams.sessionInfo = '';
      queryParams.mainProducts = '';
      
      // 重置届数选择
      selectedSession.value = '';
      
      // 重置所有筛选器
      Object.keys(filters).forEach(key => {
        filters[key] = [];
        checkAll[key] = false;
        isIndeterminate[key] = false;
      });
      
      // 重置搜索框
      companyTypeSearch.value = '';
      companyScaleSearch.value = '';
      
      // 重置分页
      currentPage.value = 1;
      
      // 重新获取数据
      fetchExhibitors();
      
      // 提示用户
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('筛选条件已重置');
      }else {
        ElMessage.success('Filters reset');
      }

    }
    
    // 处理全选/取消全选
    const handleCheckAllChange = (filter) => {
      if (checkAll[filter]) {
        // 全选
        filters[filter] = [...allFilterOptions[filter]];
        isIndeterminate[filter] = false;
      } else {
        // 取消全选
        filters[filter] = [];
        isIndeterminate[filter] = false;
      }
      
      // 对于任何类型的筛选器变化，都触发后端请求
      currentPage.value = 1; // 重置到第一页
      fetchExhibitors();
    }

    const handleContactChange = () => {
      currentPage.value = 1;
      fetchExhibitors();
    };
    
    // 处理筛选器变化
    const handleFilterChange = (filter) => {
      // 获取筛选器该类别的总数
      const totalCount = allFilterOptions[filter].length;
      
      // 设置部分选中状态
      if (filters[filter].length === 0) {
        checkAll[filter] = false;
        isIndeterminate[filter] = false;
      } else if (filters[filter].length === totalCount) {
        checkAll[filter] = true;
        isIndeterminate[filter] = false;
      } else {
        checkAll[filter] = false;
        isIndeterminate[filter] = true;
      }
      
      // 对于任何类型的筛选器变化，都触发后端请求
      currentPage.value = 1; // 重置到第一页
      fetchExhibitors();
    }
    
    // 获取所有广交会参展商数据
    const fetchExhibitors = async () => {
      loading.value = true;
      errorMsg.value = '';
      // 记录搜索次数
      let key = 'searchCount_cantonExhibitors';
      let count = parseInt(localStorage.getItem(key) || '0');
      localStorage.setItem(key, count + 1);
      
      try {
        // 准备请求参数
        const params = {
          keyword: searchKeyword.value,
          product: searchProduct.value,
          page: currentPage.value,
          size: pageSize.value
        };
        
        // 届数筛选参数
        if (selectedSession.value) {
          // 直接传递届数数字，不带"第x届"的格式
          params.sessionInfo = selectedSession.value;
        }
        
        // 添加企业类型筛选参数
        if (filters.companyType && filters.companyType.length > 0) {
          params.companyType = filters.companyType.join(',');
        }
        
        // 添加企业规模筛选参数
        if (filters.companyScale && filters.companyScale.length > 0) {
          params.companyScale = filters.companyScale.join(',');
        }

        // 添加联系方式筛选参数
        if (filters.contact && filters.contact.length > 0) {
          params.hasContact = filters.contact.join(',');
        }
        console.log("params", params)
        const response = await getCantonFairExhibitors(params);
        
        // 检查响应状态码
        if (response.code === 200) {
          // 处理可能的嵌套数据结构
          const responseData = response.data && response.data.records ? response.data.records : (Array.isArray(response.data) ? response.data : []);
          const totalCount = response.data && response.data.total ? response.data.total : (response.total || 0);
          
          if (Array.isArray(responseData)) {
            if (responseData.length === 0) {
              if (getCurrentLanguage() === 'zh'){
                errorMsg.value = '没有找到参展商数据，请尝试其他搜索条件';
              }else {
                errorMsg.value = 'No exhibitor data found, please try other search conditions';
              }

              exhibitors.value = [];
            } else {
              // 处理数据
              exhibitors.value = responseData.map(item => {

                // 添加UI交互所需的扩展属性，同时将extendedFields展开到顶层
                const processedItem = {
                  ...item,
                  ...(item.extendedFields || {}),
                  // 确保关键字段有默认值
                  province: item.province || '未知',
                  city: item.city || '未知',
                  expanded: false
                };
                
                // 处理可能的字段命名差异
                if (processedItem.countryRegion) {
                  processedItem.province = processedItem.countryRegion;
                }
                
                // 处理companyScale和enterpriseScale字段兼容
                if (processedItem.companyScale) {
                  processedItem.enterpriseScale = processedItem.companyScale;
                } else if (processedItem.enterpriseScale) {
                  processedItem.companyScale = processedItem.enterpriseScale;
                }
                
                // 处理companyType和enterpriseType字段兼容
                if (processedItem.companyType) {
                  processedItem.enterpriseType = processedItem.companyType;
                } else if (processedItem.enterpriseType) {
                  processedItem.companyType = processedItem.enterpriseType;
                }
                
                // 处理sessionInfo格式
                if (processedItem.sessionInfo && processedItem.sessionInfo.startsWith('[') && processedItem.sessionInfo.endsWith(']')) {
                  try {
                    const sessions = JSON.parse(processedItem.sessionInfo);
                    if (Array.isArray(sessions) && sessions.length > 0) {
                      processedItem.sessionInfo = `第${sessions[0]}届`;
                    }
                  } catch (e) {

                  }
                }
                
                // 处理exhibitionHistory格式
                if (processedItem.exhibitionHistory && processedItem.exhibitionHistory.startsWith('[') && processedItem.exhibitionHistory.endsWith(']')) {
                  try {
                    const history = JSON.parse(processedItem.exhibitionHistory);
                    if (Array.isArray(history)) {
                      processedItem.exhibitionHistory = history.map(h => `${h}届`).join(',');
                    }
                  } catch (e) {

                  }
                }
                
                // 处理mainProducts字段可能的格式差异
                if (processedItem.mainProducts) {
                  // 如果已经是字符串，不处理
                  if (typeof processedItem.mainProducts !== 'string') {
                    try {
                      // 尝试将对象或数组转为字符串
                      processedItem.mainProducts = JSON.stringify(processedItem.mainProducts);
                    } catch (e) {
                      processedItem.mainProducts = String(processedItem.mainProducts || '');
                    }
                  }
                }
                
                // 确保所有需要的字段都有有效值
                const requiredFields = ['sessionInfo', 'mainProducts', 'companyScale', 'enterpriseType'];
                requiredFields.forEach(field => {
                  if (!processedItem[field]) {
                    processedItem[field] = '-';
                  }
                });
                
                return processedItem;
              });
            }
            
            // 更新总数，限制最大显示为10000
            totalExhibitors.value = Math.min(totalCount || exhibitors.value.length, 10000);
            // 确保总数至少为1，避免分页控件不显示
            // if (totalExhibitors.value <= 0) {
            //   totalExhibitors.value = 1;
            // }
            
            // 从响应中获取当前页码，确保分页控件与后端数据同步
            if (response.data && response.data.current) {
              // 使用nextTick确保在DOM更新后再设置当前页码
              const pageFromServer = response.data.current;
              nextTick(() => {
                currentPage.value = pageFromServer;
              });
            }
          } else {
            if (getCurrentLanguage() === 'zh'){
              errorMsg.value = '暂时无法获取参展商数据，请稍后再试';
            } else {
              errorMsg.value = 'Unable to get exhibitor data, please try again later';
            }

            exhibitors.value = [];
          }
        } else {
          // 非200状态码
          currentPage.value = 1;
        }
        
        // 提取筛选器选项
        extractFilterOptions();
        
      } catch (error) {
        if (getCurrentLanguage() === 'zh'){
          errorMsg.value = '获取参展商数据失败，请确保已登录';
        } else {
          errorMsg.value = 'Failed to get exhibitor data, please make sure you have logged in';
        }

        ElMessage.error(errorMsg.value);
        exhibitors.value = [];
      } finally {
        loading.value = false;
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      // 清空其他查询参数
      queryParams.exhibitorName = '';
      queryParams.sessionInfo = '';
      queryParams.mainProducts = '';
      
      // 重置到第一页
      currentPage.value = 1;
      fetchExhibitors();
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchKeyword.value = '';
      searchProduct.value = '';
      queryParams.exhibitorName = '';
      queryParams.sessionInfo = '';
      queryParams.mainProducts = '';
      // 不自动触发请求
    }
    
    // 切换筛选器展开状态
    const toggleFilter = (filter) => {
      expanded[filter] = !expanded[filter];
    }
    
    // 切换参展商详情展示
    const toggleExhibitorDetails = (exhibitor) => {
      exhibitor.expanded = !exhibitor.expanded;
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1; // 重置到第一页
      // 重新获取数据
      fetchExhibitors();
    }
    
    // 处理分页变化
    const handlePageChange = (page) => {
      currentPage.value = page;
      
      // 始终重新请求数据以获取当前页的展商信息
      fetchExhibitors();
    }
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        // 先获取符合条件的记录数量
        await fetchExportCount()
        
        // 再获取用户余额
        await fetchUserBalance()
        
        // 显示导出对话框 - 直接设置为true并添加调试日志
        exportDialogVisible.value = true
        
        // 确保对话框显示
        setTimeout(() => {
          if (!exportDialogVisible.value) {
            exportDialogVisible.value = true
          }
        }, 100)
      } catch (error) {
        if (getCurrentLanguage() === 'zh'){
          ElMessage.error('准备导出失败，请稍后重试')
        } else {
          ElMessage.error('Export failed, please try again later')
        }

        // 尝试直接显示导出对话框
        exportDialogVisible.value = true
      } finally {
        exportLoading.value = false
      }
    }
    
    // 获取符合条件的记录数量
    const fetchExportCount = async () => {
      try {
        // 构建查询参数
        const params = {};
        
        // 添加搜索关键词
        if (searchKeyword.value) {
          params.keyword = searchKeyword.value;
        }

        if (searchProduct.value) {
          params.product = searchProduct.value;
        }
        
        // 添加筛选条件: 届数
        if (selectedSession.value) {
          params.sessionInfo = selectedSession.value;
        }
        
        // 添加筛选条件: 公司类型
        if (filters.companyType && filters.companyType.length > 0) {
          params.companyType = filters.companyType.join(',');
        }
        
        // 添加筛选条件: 公司规模
        if (filters.companyScale && filters.companyScale.length > 0) {
          params.companyScale = filters.companyScale.join(',');
        }

        if (filters.contact && filters.contact.length > 0) {
          params.hasContact = filters.contact.join(',');
        }
        
        const response = await getCantonFairExhibitorsCount(params);

        if (response.code === 200) {
          // 从响应中提取count字段
          const count = response.data.count || 0;

          // 限制显示的最大记录数为50000
          totalMatchCount.value = Math.min(count, 50000);
          exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
          return count;
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(response.msg || '获取记录数量失败');
          } else {
            ElMessage.error('Failed to get record count');
          }
          return 0;
        }
      } catch (error) {
        if (getCurrentLanguage() === 'zh'){
          ElMessage.error('获取记录数量失败，请稍后重试');
        } else {
          ElMessage.error('Failed to get record count, please try again later');
        }
        return 0;
      }
    }
    
    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const response = await getUserBalanceInfo();

        if (response.code === 200 && response.data) {
          userBalance.value = response.data;
          
          // 如果当前设置的导出数量超过余额，显示警告
          if (exportCount.value > userBalance.value.exportQuotaRemaining) {
            ElMessage({
              message: t('export.warning.balance'),
              type: 'warning',
              duration: 5000
            });
          }
          
          return response.data;
        } else {
          // 设置默认值避免undefined错误
          userBalance.value = { exportQuotaRemaining: 0 };
          if (getCurrentLanguage() === 'zh'){
            ElMessage.error(response.msg || '获取余额信息失败');
          } else {
            ElMessage.error('Failed to get balance info');
          }
          return { exportQuotaRemaining: 0 };
        }
      } catch (error) {
        // 设置默认值避免undefined错误
        userBalance.value = { exportQuotaRemaining: 0 };
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('获取余额信息失败，请稍后重试');
        }else {
          ElMessage.error('Failed to get balance info, please try again later');
        }
        return { exportQuotaRemaining: 0 };
      }
    }
    
    // 执行导出操作
    const doExport = async () => {
      // 检查字段选择
      if (isNoFieldsSelected.value) {
        ElMessage.error(t('export.error.noFieldsSelected'));
        return;
      }

      // 检查导出数量
      if (isExportCountExceeded.value) {
        ElMessage.error(t('export.error.countExceeded', { maxCount: totalMatchCount.value }));
        return;
      }

      // 检查导出上限
      if (isExportLimitExceeded.value) {
        ElMessage.error(t('export.error.limitExceeded'));
        return;
      }

      // 检查余额
      if (isBalanceInsufficient.value) {
        ElMessage.error(t('export.error.balanceInsufficient'));
        return;
      }

      // 确保导出数量是有效的数字
      if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
        ElMessage.error(t('export.error.invalidCount'));
        return;
      }
      
      exportLoading.value = true;
      exportDialogVisible.value = false;
      
      // 如果导出数量大于10000，显示特殊提示
      if (exportCount.value > 10000) {
        ElMessage({
          message: t('export.warning.largeData'),
          type: 'info',
          duration: 10000
        });
      } else {
        ElMessage({
          message: t('export.info.exporting'),
          type: 'info',
          duration: 5000
        });
      }
      
      try {
        // 准备导出参数对象
        const exportParams = {
          exportCount: Number(exportCount.value), // 确保转换为数字类型
          selectedFields: selectedFields.value.join(','), // 添加选中的字段列表
          language: currentLanguage.value // 添加当前语言参数
        };

        // 添加搜索关键词
        if (searchKeyword.value) {
          exportParams.keyword = searchKeyword.value;
        }

        if (searchProduct.value) {
          exportParams.product = searchProduct.value;
        }
        
        // 添加筛选条件
        if (selectedSession.value) {
          exportParams.sessionInfo = selectedSession.value;
        }
        
        if (filters.companyType && filters.companyType.length > 0) {
          exportParams.companyType = filters.companyType.join(',');
        }
        
        if (filters.companyScale && filters.companyScale.length > 0) {
          exportParams.companyScale = filters.companyScale.join(',');
        }

        if (filters.contact && filters.contact.length > 0) {
          exportParams.hasContact = filters.contact.join(',');
        }
        console.log("exportParams", exportParams)
        // 发送请求
        const response = await exportCantonFairExhibitors(exportParams);
        
        // 检查响应是否为blob
        if (!response || !response.data) {
          if (getCurrentLanguage() === 'zh') {
            throw new Error('导出失败：服务器未返回数据');
          } else {
            throw new Error('Export failed: server did not return data');
          }
        }
        
        if (!(response.data instanceof Blob)) {
          if (getCurrentLanguage() === 'zh'){
            throw new Error('导出失败：服务器返回格式不正确');
          } else {
            throw new Error('Export failed: server returned invalid format');
          }
        }
        
        // 获取Content-Type
        const contentType = response.headers && response.headers['content-type'] 
          ? response.headers['content-type'] 
          : 'application/vnd.ms-excel'
        
        // 检查是否是错误响应
        if (contentType.includes('json')) {
          // 可能是错误响应，尝试解析
          const reader = new FileReader();
          
          // 使用Promise包装FileReader
          const readJsonResponse = new Promise((resolve, reject) => {
            reader.onload = function() {
              try {
                const result = reader.result;
                const errorResponse = JSON.parse(result);
                resolve(errorResponse);
              } catch (e) {
                if (getCurrentLanguage() === 'zh') {
                  reject(new Error('导出失败：无法识别的错误'));
                } else {
                  reject(new Error('Export failed: unable to recognize error'));
                }
              }
            };
            reader.onerror = function(e) {
              if (getCurrentLanguage() === 'zh') {
                reject(new Error('导出失败：无法读取错误响应'));
              } else {
                reject(new Error('Export failed: unable to read error response'));
              }
            };
          });
          
          reader.readAsText(response.data);
          
          try {
            const errorData = await readJsonResponse;
            // 显示具体的错误信息
            const errorMessage = errorData.msg || errorData.message || '未知错误';
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(`导出失败：${errorMessage}`);
            } else {
              ElMessage.error(`Export failed`);
            }

            // 如果错误与参数相关，可能需要提示用户修改导出数量
            if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
              if (getCurrentLanguage() === 'zh'){
                ElMessage.warning('请检查导出数量是否正确设置');
              }else {
                ElMessage.warning('Please check if the export count is set correctly');
              }
            }
            
            return;
          } catch (e) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(e.message || '导出失败：无法识别的错误');
            } else {
              ElMessage.error(e.message || 'Export failed: unable to recognize error');
            }
            return;
          }
        }
        
        // 创建Blob对象
        const blob = new Blob([response.data], { type: contentType })
        
        // 获取文件名
        let fileName = '广交会展商数据.xlsx'
        const disposition = response.headers && response.headers['content-disposition']
        if (disposition && disposition.includes('filename=')) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
          const matches = filenameRegex.exec(disposition)
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '')
            try {
              fileName = decodeURIComponent(fileName)
            } catch (e) {
            }
          }
        }
        
        // 下载文件
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        // 更新用户余额
        await fetchUserBalance();

        if (getCurrentLanguage() === 'zh'){
          ElMessage.success('导出成功');
        } else {
          ElMessage.success('Export successful');
        }
      } catch (error) {

        // 处理超时错误
        if (error.message && error.message.includes('timeout')) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('导出请求超时，数据量可能过大，请减少导出数量或稍后再试');
          } else {
            ElMessage.error('Export request timed out, data volume may be too large, please reduce export count or try again later');
          }
          return;
        }
        
        // 尝试从错误响应中解析错误信息
        let errorMsg = '导出失败，请稍后重试';
        if (error.response && error.response.data) {
          try {
            // 尝试解析blob数据为JSON
            if (error.response.data instanceof Blob) {
              const text = await error.response.data.text();
              try {
                const jsonResponse = JSON.parse(text);
                errorMsg = jsonResponse.msg || jsonResponse.message || '导出失败，服务器返回错误';
              } catch (parseError) {

              }
            }
          } catch (parseError) {

          }
        }
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(errorMsg);
        } else {
          ElMessage.error('Export failed, please try again later');
        }
      } finally {
        exportLoading.value = false;
      }
    }
    
    // 为网站URL添加http前缀
    const addHttpPrefix = (url) => {
      if (!url) return '#';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      return 'http://' + url;
    }
    
    // 获取参展商头像URL
    const getAvatarUrl = (companyName) => {
      if (!companyName) return '';
      // 使用默认的动物头像服务
      return `https://api.dicebear.com/7.x/bottts/svg?seed=${encodeURIComponent(companyName)}&backgroundColor=b6e3f4,c0aede,d1d4f9`;
    }
    
    // 处理头像加载错误
    const handleAvatarError = (e) => {
      e.target.src = 'https://api.dicebear.com/7.x/bottts/svg?seed=fallback&backgroundColor=b6e3f4';
    }

    // 处理电话、传真、网址和邮箱的点击事件
    const showFullContactInfo = async (exhibitor, field) => {
      // 只有当信息包含星号时才需要查询完整信息
      if (!(exhibitor[field] && exhibitor[field].includes('*'))) {
        return;
      }
      
      try {
        // 弹出确认对话框
        await ElMessageBox.confirm(
          t('canton.exhibitor.confirm.view.contact'),
          t('canton.exhibitor.view.full.contact'),
          {
            confirmButtonText: t('canton.exhibitor.confirm'),
            cancelButtonText: t('canton.exhibitor.cancel'),
            type: 'warning'
          }
        );
        
        // 获取sessionInfo，优先使用exhibitor.sessionInfo，如果没有则使用selectedSession
        const sessionInfo = exhibitor.sessionInfo || selectedSession.value;
        
        // 从sessionInfo中提取届数数字
        let sessionNumber = '';
        if (sessionInfo) {
          const match = sessionInfo.match(/\d+/);
          sessionNumber = match ? match[0] : '';
        }
        
        if (!sessionNumber) {
          ElMessage.error(t('canton.exhibitor.session.required'));
          return;
        }
        // 用户点击确认，调用API获取完整信息
        const response = await getExhibitorFullContactInfo(exhibitor.id, sessionNumber, field);
        
        if (response.code === 200 && response.data) {
          // 更新当前参展商的联系信息
          if (response.data[field]) {
            // 直接使用返回的字段值更新对应字段
            exhibitor[field] = response.data[field];
          }
          
          ElMessage.success(t('canton.exhibitor.contact.view.success'));
        } else {
          ElMessage.error(response.msg || t('canton.exhibitor.contact.view.error'));
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 处理特定错误，如余额不足
          if (error.response && error.response.data && error.response.data.msg) {
            ElMessage.error(error.response.data.msg);
          } else {
            ElMessage.error(t('canton.exhibitor.contact.view.error'));
          }
        }
      }
    }
    
    // 监视筛选器变化
    const watchFilters = () => {
      // 监视每个筛选字段
      Object.keys(filters).forEach(key => {
        watch(() => filters[key], () => {
          handleFilterChange(key);
        }, { deep: true });
      });
    };
    
    // 监听语言变化
    const watchLanguageChange = () => {
      watch(() => getCurrentLanguage(), (newLang, oldLang) => {
        if (newLang !== oldLang) {
          // 语言变化时强制更新筛选器
          nextTick(() => {
            // 不需要重新请求数据，只需要刷新UI
          });
        }
      });
    };
    
    // 组件挂载时加载数据
    onMounted(() => {
      // 添加查看联系信息相关翻译
      addTranslation('canton.exhibitor.filter.contact.mobile', {
        zh: '手机号',
        en: 'Mobile'
      });
      addTranslation('canton.exhibitor.filter.contact', {
        zh: '联系方式',
        en: 'Contact Methods'
      });

      addTranslation('canton.exhibitor.filter.contact.phone', {
        zh: '电话',
        en: 'Phone'
      });

      addTranslation('canton.exhibitor.filter.contact.fax', {
        zh: '传真',
        en: 'Fax'
      });

      addTranslation('canton.exhibitor.filter.contact.email', {
        zh: '邮箱',
        en: 'Email'
      });

      addTranslation('canton.exhibitor.filter.contact.website', {
        zh: '网站',
        en: 'Website'
      });
      addTranslation('canton.exhibitor.view.full.contact.tooltip', {
        zh: '点击消耗一次次数查看完整信息',
        en: 'Click to view full information (costs 1 credit)'
      });

      addTranslation('canton.exhibitor.confirm.view.contact', {
        zh: '查看完整联系信息将消耗一次查看次数，是否继续？',
        en: 'Viewing full contact information will cost 1 credit. Continue?'
      });
      
      // 添加导出相关翻译
      addTranslation('export.dialog.title', {
        zh: '导出数据',
        en: 'Export Data'
      });

      addTranslation('export.matching.records', {
        zh: '符合条件的记录数',
        en: 'Matching records'
      });

      addTranslation('export.current.balance', {
        zh: '当前导出余额',
        en: 'Current export balance'
      });

      addTranslation('export.note', {
        zh: '注意: 每导出一条记录将消耗一点导出额度',
        en: 'Note: Each exported record will consume one export credit'
      });

      addTranslation('export.enter.count', {
        zh: '请输入要导出的记录数:',
        en: 'Please enter the number of records to export:'
      });

      addTranslation('export.cancel', {
        zh: '取消',
        en: 'Cancel'
      });

      addTranslation('export.confirm', {
        zh: '确认导出',
        en: 'Confirm Export'
      });

      addTranslation('export.warning.exceed', {
        zh: '导出数量不能超过符合条件的记录数',
        en: 'Export quantity cannot exceed the number of matching records'
      });

      addTranslation('export.warning.balance', {
        zh: '导出余额不足',
        en: 'Insufficient export balance'
      });

      addTranslation('export.warning.limit', {
        zh: '导出数量不能超过50000条',
        en: 'Export quantity cannot exceed 50,000 records'
      });
      
      // 添加导出错误消息的翻译
      addTranslation('export.error.countExceeded', {
        zh: '导出数量超过符合条件的记录数，最多可导出{maxCount}条记录',
        en: 'Export count exceeds matching records, maximum {maxCount} records allowed'
      });
      
      addTranslation('export.error.limitExceeded', {
        zh: '导出数量超过系统限制，最多可导出50,000条记录',
        en: 'Export count exceeds system limit, maximum 50,000 records allowed'
      });
      
      addTranslation('export.error.balanceInsufficient', {
        zh: '导出余额不足，请充值后再试',
        en: 'Insufficient export balance, please recharge and try again'
      });
      
      addTranslation('export.error.invalidCount', {
        zh: '请输入有效的导出数量',
        en: 'Please enter a valid export count'
      });
      
      addTranslation('export.error.noFieldsSelected', {
        zh: '请至少选择一个导出字段',
        en: 'Please select at least one export field'
      });
      
      addTranslation('export.max.limit.notice', {
        zh: '系统最多支持导出50,000条记录',
        en: 'The system supports exporting up to 50,000 records'
      });
      
      addTranslation('canton.exhibitor.view.full.contact', {
        zh: '查看完整联系信息',
        en: 'View Full Contact Information'
      });
      
      addTranslation('canton.exhibitor.confirm', {
        zh: '确认',
        en: 'Confirm'
      });
      
      addTranslation('canton.exhibitor.cancel', {
        zh: '取消',
        en: 'Cancel'
      });
      
      addTranslation('canton.exhibitor.contact.view.success', {
        zh: '联系信息获取成功',
        en: 'Contact information retrieved successfully'
      });
      
      addTranslation('canton.exhibitor.contact.view.error', {
        zh: '获取联系信息失败，请稍后重试',
        en: 'Failed to retrieve contact information, please try again later'
      });
      
      addTranslation('canton.exhibitor.session.required', {
        zh: '无法确定广交会届数，请选择一个届数后重试',
        en: 'Cannot determine Canton Fair session, please select a session and try again'
      });
      
      addTranslation('canton.exhibitor.establish.year', {
        zh: '成立年份',
        en: 'Establishment Year'
      });
      
      addTranslation('canton.exhibitor.matching.records', {
        zh: '符合条件的企业数量',
        en: 'Matching enterprises'
      });

      // 初始化选中的字段
      initSelectedFields();
      
      // 监听语言变化
      watchLanguageChange();
      
      // 首先获取所有可能的筛选选项
      fetchAllFilterOptions().then(() => {
        // 获取默认的展商数据
        fetchExhibitors();
      });
    });
    
    // 提取筛选器选项
    const extractFilterOptions = () => {
      // 预设的企业类型选项 - 按照逻辑分类排序
      const presetCompanyTypes = [
        '未知', '-',
        // 国有和集体企业
        '国有企业', '集体企业',
        // 私营和股份制企业
        '私营企业', '有限责任公司', '股份有限公司', '股份合作企业', '联营企业',
        // 外资企业
        '中外合资企业', '中外合作企业', '外商独资企业', '港澳台投资企业',
        // 专业类型企业
        '生产企业', '外贸企业', '工贸企业', '科研院所',
        // 其他
        '其他企业'
      ];
      
      // 预设的企业规模选项 - 按照新的要求更新
      const presetCompanyScales = [
        '未知', '少于50人', '1-50人', '51-100人', '50~150', '101-500人',
        '150~500', '500人以上', '500~1000', '1000~5000', '5000~10000', '10000人以上'
      ];
      
      // 使用预设选项初始化筛选选项
      allFilterOptions.companyType = [...new Set(presetCompanyTypes)];
      allFilterOptions.companyScale = [...new Set(presetCompanyScales)];
      
      // 如果有返回数据，添加从展商数据中提取的唯一选项
      if (exhibitors.value.length > 0) {
        const tempTypes = new Set(presetCompanyTypes);
        const tempScales = new Set(presetCompanyScales);
        
        // 从当前数据中提取唯一的企业类型和规模
        exhibitors.value.forEach(exhibitor => {
          // 提取企业类型
          if (exhibitor.enterpriseType) {
            tempTypes.add(exhibitor.enterpriseType);
          }
          if (exhibitor.companyType) {
            tempTypes.add(exhibitor.companyType);
          }
          
          // 提取企业规模
          if (exhibitor.companyScale) {
            tempScales.add(exhibitor.companyScale);
          }
          if (exhibitor.enterpriseScale) {
            tempScales.add(exhibitor.enterpriseScale);
          }
        });
        
        // 更新选项
        allFilterOptions.companyType = Array.from(tempTypes);
        allFilterOptions.companyScale = Array.from(tempScales);
      }
    }
    
    // 提取所有可能的筛选选项（可在用户首次加载页面时调用）
    const fetchAllFilterOptions = async () => {
      try {
        // 对每个广交会届数进行少量数据查询，收集所有可能的筛选值
        const sessions = ["125", "126", "127", "128", "129", "130", "134", "135", "136", "137"];
        const tempTypes = new Set();
        const tempScales = new Set();
        
        // 默认选项
        tempTypes.add('未知');
        tempTypes.add('--');
        tempScales.add('未知');
        tempScales.add('--');
        
        // 对每个届数查询一些数据
        for (const session of sessions) {
          const params = {
            sessionInfo: session,
            page: 1,
            size: 10
          };
          
          try {
            const response = await getCantonFairExhibitors(params);
            if (response.code === 200) {
              const records = response.data && response.data.records ? response.data.records : [];
              
              // 收集企业类型和规模
              records.forEach(item => {
                if (item.companyType) tempTypes.add(item.companyType);
                if (item.enterpriseType) tempTypes.add(item.enterpriseType);
                if (item.companyScale) tempScales.add(item.companyScale);
                if (item.enterpriseScale) tempScales.add(item.enterpriseScale);
              });
            }
          } catch (error) {

          }
        }
        
        // 更新筛选选项
        allFilterOptions.companyType = Array.from(tempTypes);
        allFilterOptions.companyScale = Array.from(tempScales);
      } catch (error) {

      }
    }
    
    // 导出相关的状态
    const exportDialogVisible = ref(false)
    const totalMatchCount = ref(0)
    const exportCount = ref(0)
    const userBalance = ref({
      exportQuotaRemaining: 0
    })
    const isExportCountExceeded = computed(() => {
      return exportCount.value > totalMatchCount.value
    })
    const isBalanceInsufficient = computed(() => {
      return exportCount.value > userBalance.value.exportQuotaRemaining
    })
    const isExportLimitExceeded = computed(() => {
      return exportCount.value > 50000
    })

    // 字段选择相关变量
    const selectedFields = ref([]);
    // 使用全局响应式语言变量，确保语言切换时实时更新
    const currentLanguage = globalCurrentLanguage;

    // 创建国际化字段配置
    const createFieldsConfig = () => {
      return [
        { key: 'companyName', labelKey: 'exhibitor.field.companyName', selected: true },
        { key: 'boothNumber', labelKey: 'exhibitor.field.boothNumber', selected: true },
        { key: 'contactPerson', labelKey: 'exhibitor.field.contactPerson', selected: true },
        { key: 'address', labelKey: 'exhibitor.field.address', selected: true },
        { key: 'postalCode', labelKey: 'exhibitor.field.postalCode', selected: true },
        { key: 'category', labelKey: 'exhibitor.field.industry', selected: true },
        { key: 'city', labelKey: 'exhibitor.field.city', selected: true },
        { key: 'province', labelKey: 'exhibitor.field.province', selected: true },
        { key: 'extendedFields.website', labelKey: 'exhibitor.field.website', selected: true },
        { key: 'establishmentYear', labelKey: 'exhibitor.field.establishYear', selected: false },
        { key: 'extendedFields.sessionInfo', labelKey: 'exhibitor.field.sessionInfo', selected: true },
        { key: 'extendedFields.mainProducts', labelKey: 'exhibitor.field.mainProducts', selected: true },
        { key: 'extendedFields.mobilePhone', labelKey: 'exhibitor.field.mobilePhone', selected: true },
        { key: 'extendedFields.phone', labelKey: 'exhibitor.field.phone', selected: true },
        { key: 'extendedFields.fax', labelKey: 'exhibitor.field.fax', selected: false },
        { key: 'extendedFields.email', labelKey: 'exhibitor.field.email', selected: true },
        // 新增导出字段
        { key: 'extendedFields.companyType', labelKey: 'exhibitor.field.companyType', selected: true },
        { key: 'extendedFields.companyScale', labelKey: 'exhibitor.field.companyScale', selected: true },
        { key: 'extendedFields.recentExhibitionHistory', labelKey: 'exhibitor.field.recentExhibitionHistory', selected: false },
        { key: 'extendedFields.registeredCapital', labelKey: 'exhibitor.field.registeredCapital', selected: false },
        { key: 'extendedFields.companyProfile', labelKey: 'exhibitor.field.companyProfile', selected: false }
      ];
    };

    const allFields = ref(createFieldsConfig());

    // 字段选择相关函数
    const initSelectedFields = () => {
      selectedFields.value = allFields.value.filter(field => field.selected).map(field => field.key);
    };

    const updateSelectedFields = () => {
      const newSelectedFields = allFields.value.filter(field => field.selected).map(field => field.key);
      selectedFields.value = newSelectedFields;
    };

    const selectAllFields = () => {
      allFields.value.forEach(field => {
        field.selected = true;
      });
      updateSelectedFields();
    };

    const selectNoFields = () => {
      allFields.value.forEach(field => {
        field.selected = false;
      });
      updateSelectedFields();
    };
    
    // 验证导出数量
    const validateExportCount = (value) => {
      // 检查是否超出余额限制
      if (value > userBalance.value.exportQuotaRemaining) {
        // 显示余额不足警告
        ElMessage({
          message: t('export.error.balanceInsufficient'),
          type: 'warning',
          duration: 5000
        });
      }
      // 检查是否超出最大导出限制
      else if (value > 50000) {
        ElMessage({
          message: t('export.error.limitExceeded'),
          type: 'warning',
          duration: 5000
        });
      }
      // 检查是否超出符合条件的记录数
      else if (value > totalMatchCount.value) {
        ElMessage({
          message: t('export.error.countExceeded', { maxCount: totalMatchCount.value }),
          type: 'warning',
          duration: 5000
        });
      }
    };

    const isAllFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => field.selected);
      return result;
    });

    const isNoFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => !field.selected);
      return result;
    });
    

    

    
    return {
      loading,
      exportLoading,
      errorMsg,
      exhibitors,
      currentPage,
      pageSize,
      totalExhibitors,
      searchKeyword,
      searchProduct,
      selectedSession,
      filters,
      expanded,
      checkAll,
      isIndeterminate,
      companyTypeSearch,
      companyScaleSearch,
      filteredCompanyTypes,
      filteredCompanyScales,
      filteredExhibitors,
      paginatedExhibitors,
      getAvatarUrl,
      handleAvatarError,
      toggleFilter,
      handleCheckAllChange,
      handleFilterChange,
      handleContactChange,
      resetSearch,
      resetAllFilters,
      toggleExhibitorDetails,
      handleSearch,
      handleSessionChange,
      handleSizeChange,
      handlePageChange,
      exportData,
      fetchExhibitors,
      addHttpPrefix,
      t,
      getLocalizedCompanyType,
      getLocalizedCompanyScale,
      showFullContactInfo,
      // 添加导出相关的变量和方法
      exportDialogVisible,
      exportCount,
      totalMatchCount,
      userBalance,
      isExportCountExceeded,
      isBalanceInsufficient,
      isExportLimitExceeded,
      doExport,
      // 字段选择相关
      selectedFields,
      allFields,
      currentLanguage,
      initSelectedFields,
      updateSelectedFields,
      selectAllFields,
      selectNoFields,
      isAllFieldsSelected,
      isNoFieldsSelected,
      validateExportCount
    }
  }
}
</script>

<style scoped>
.canton-fair-exhibitors-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.main-container {
  display: flex;
  min-height: calc(100vh - 60px); /* 减去顶部导航的高度 */
  position: relative; /* 添加相对定位 */
  flex: 1;
  height: 100%;
  overflow: hidden; /* 防止页面级滚动，只让内容区滚动 */
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto; /* 只滚动右侧内容区 */
  height: 100%;
  display: flex;
  flex-direction: column; /* 确保内容区是垂直排列的 */
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  text-align: center; /* 文本居中 */
}

.search-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  text-align: center; /* 标题居中 */
}

.search-box-container {
  width: 100%;
  max-width: 1000px; /* 搜索框宽度从500px改为400px */
}

.search-input {
  width: 300px;
  font-size: 16px; /* 增加字体大小 */
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.search-input :deep(.el-input__inner) {
  font-size: 16px; /* 确保输入框内的文字也变大 */
  height: 45px; /* 增加高度以适应大字体 */
  text-align: center; /* 文字居中显示 */
}

.mt-10 {
  margin-top: 10px;
}

/* 主内容区布局 */
.exhibitors-main {
  display: flex;
  gap: 20px; /* 筛选器与内容区之间的间隔 */
  flex: 1;
}

/* 筛选侧边栏样式 */
.filter-sidebar-container {
  width: 280px;
  flex-shrink: 0; /* 防止侧边栏宽度被压缩 */
  position: relative; /* 为固定定位做准备 */
}

.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  position: sticky; /* 使筛选器在滚动时保持可见 */
  top: 20px; /* 距离顶部的距离 */
  max-height: calc(100vh - 100px); /* 最大高度，确保在小屏幕上可以滚动 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
}

/* 重置筛选器按钮 */
.reset-filter-container {
  margin-bottom: 15px;
  text-align: center;
}

.reset-filter-btn {
  width: 100%;
}

/* 筛选组样式 */
.filter-group {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden; /* 防止内容溢出 */
}

.filter-group.expanded {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.filter-content {
  padding: 15px;
  max-height: 250px; /* 限制最大高度 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
}

/* 筛选器内搜索框 */
.filter-search {
  margin-bottom: 10px;
}

/* 右侧数据内容区 */
.data-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 导出模块 */
.export-module {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.export-info {
  font-size: 14px;
  color: #606266;
}

.export-count {
  font-weight: bold;
  color: #409EFF;
  margin-left: 5px;
}

.export-module-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 参展商卡片列表 */
.exhibitor-card-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

/* 骨架屏 */
.skeleton-loading {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.skeleton-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 250px;
}

.skeleton-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.skeleton-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #eee;
  margin-right: 15px;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-title {
  width: 70%;
  height: 20px;
  background-color: #eee;
  animation: skeleton-loading 1.5s infinite;
}

.skeleton-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.skeleton-line {
  height: 15px;
  background-color: #eee;
  animation: skeleton-loading 1.5s infinite;
}

@keyframes skeleton-loading {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

/* 参展商卡片样式 */
.exhibitor-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
}

.exhibitor-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.company-info {
  display: flex;
  align-items: center;
}

.company-avatar {
  margin-right: 15px;
}

.cartoon-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.company-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.card-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 10px 0;
}

.info-button-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-basic-info {
  flex: 1;
}

.basic-info-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.full-width {
  flex: 1 1 100%;
}

.info-label {
  color: #909399;
  margin-right: 5px;
  font-size: 14px;
}

.info-value {
  color: #606266;
  font-size: 14px;
  word-break: break-word;
}

.detail-button-container {
  margin-left: 10px;
}

.detail-btn {
  min-width: 80px;
  transition: all 0.3s;
}

/* 为收起状态添加特殊样式 */
.el-button.detail-btn:not(.is-plain) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 详细信息区域 */
.card-content {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.info-table-wrapper {
  overflow-x: auto; /* 确保表格在小屏幕上可以滚动 */
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 8px 10px;
  border-bottom: 1px solid #ebeef5;
}

.label-cell {
  width: 120px;
  color: #909399;
  font-size: 14px;
  vertical-align: top;
}

.value-cell {
  color: #606266;
  font-size: 14px;
  word-break: break-word;
}

/* 分页器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.pagination-container :deep(.el-pagination) {
  font-weight: normal;
  justify-content: center;
  width: 100%;
}

.pagination-container :deep(.el-pagination .el-pagination__total) {
  font-weight: bold;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes) {
  margin-right: 15px;
}

/* 无数据提示 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
  color: #909399;
  font-size: 14px;
}

.no-data i {
  font-size: 36px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .exhibitors-main {
    flex-direction: column;
  }
  
  .filter-sidebar-container {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .filter-sidebar {
    position: static;
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 遮蔽的联系信息样式 */
.masked-info {
  color: #409eff;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  position: relative;
  padding-right: 20px;
}

.masked-info:hover {
  text-decoration: underline;
}

.info-lock-icon {
  font-size: 14px;
  margin-left: 5px;
  color: #909399;
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 字段选择区域样式 */
.field-selection {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.field-selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.field-selection-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.field-selection-actions {
  display: flex;
  gap: 8px;
}

.field-selection-content {
  margin-top: 10px;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 10px;
}

.field-item {
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.field-item:hover {
  background-color: #f0f9ff;
}

.field-item .el-checkbox {
  width: 100%;
  cursor: pointer;
}

.field-item .el-checkbox__label {
  width: 100%;
  padding-left: 8px;
  cursor: pointer;
}

.field-unselected {
  color: #909399 !important;
  font-weight: normal;
}

.field-warning {
  color: #f56c6c;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
}
</style>